<template>
  <div class="cart">
    <van-nav-bar
      title="购物车"
      :left-text="isEit ? '编辑' : '完成'"
      @click-left="isEit = !isEit"
    />
    <div class="count">
      <van-swipe-cell v-for="(item, index) in cartList" :key="index">
        <van-checkbox
          v-model="item.ischeck"
          checked-color="#ee0a24"
          @change="checkBtn"
        ></van-checkbox>
        <van-card :thumb="`http://106.15.179.105:3000/${item.product_picture}`">
          <template #tags>
            <p>{{ item.product_name }}</p>
            <p class="tag-ct">{{ item.product_title }}</p>
            <section>
              <span style="color: red">￥{{ item.product_selling_price }}</span>
              <van-stepper v-model="item.buyNum" />
            </section>
          </template>
        </van-card>
        <template #right>
          <van-button square text="删除" type="danger" class="delete-button" @click="del(index)"/>
        </template>
      </van-swipe-cell>
    </div>
    <van-submit-bar :price="allPrice" :button-text="isEit?'提交订单':'删除选中'" @submit="onSubmit">
      <van-checkbox v-model="allCheck" @click="allBtn" checked-color="#ee0a24">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import { ref, reactive, toRefs, computed } from "vue";
import { useStore } from "vuex";
export default {
  setup() {
    const store = useStore();
    const isEit = ref(true);
    const data = reactive({
      cartList: computed(() => store.state.cartList),
      allCheck: false, // 全选的状态
      allPrice: computed(() => {
        let price = 0;
        data.cartList.forEach(item => {
          if (item.ischeck){
            price+= item.buyNum*item.product_selling_price
          }
        })
        return price*100;
      })
    });

    const onSubmit = () => { // 提交订单和删除的事件
       if (!isEit.value){
          store.commit('delSome')
       }
    }
    const allBtn = () => { // 全选的事件
       store.state.cartList.forEach(item => {
         item.ischeck = data.allCheck
       })
    }

    const checkBtn = () => { // 反选的事件
       data.allCheck = data.cartList.every(item => item.ischeck);
    }

    const del = (i) => { // 单个删除事件
       store.commit('storeDel', i);
    }
    return {
      isEit,
      ...toRefs(data),
      onSubmit,
      allBtn,
      checkBtn,
      del
    };
  },
};
</script>
<style lang="scss" scoped>
.count {
  height: calc(100% - 96px);
  overflow: auto;
}
:deep(.van-swipe-cell__wrapper) {
  display: flex;
  align-items: center;
  padding: 0 10px;
  .van-card {
    background: #fff;
    flex: 1;
  }
  .van-button {
    height: 100%;
  }
  section {
    display: flex;
    justify-content: space-between;
  }
  .tag-ct {
    margin: 15px 0;
    color: #999;
  }
}
:deep(.van-submit-bar){
  bottom: 50px;
}
</style>